package com.cuanbo.dualscreenteachfu.utils;

import android.content.Context;
import android.text.TextUtils;

import com.cuanbo.dualscreenteachfu.base.App;
import com.cuanbo.dualscreenteachfu.constant.MatrixConstant;
import com.cuanbo.dualscreenteachfu.matrix.MatrixHeartbeatThread;
import com.cuanbo.dualscreenteachfu.service.BackgroundService;

import java.util.Date;

/**
 * 连接状态监测工具
 */
public class ConnectStateUtil {
    public static long recordMatrixTime;
    //超时时间为30秒
    private static long timeoutSensor = MatrixHeartbeatThread.interval * 15;
    //超时时间为12小时
    private static long timeoutLBSensor = MatrixHeartbeatThread.interval * 30 * 60 * 12;
    //主动矩阵超时时间为60秒
    public static long timeoutMatrixInitiative = MatrixHeartbeatThread.interval * 10;
    //被动矩阵超时时间为1小时
    public static long timeoutMatrixPassive = MatrixHeartbeatThread.interval * 1800;
    private static long timeoutAirSwitch = MatrixHeartbeatThread.interval * 15;

    /**
     * 记录当前时间
     *
     * @param context 上下文对象
     * @param key     保存数据的Key
     */
    public static void recordTime(Context context, String key) {
        long nowTime = new Date().getTime();
        //LogUtil.add("checkConnectStateMatrix", key + "保存当前时间:" + DateUtil.fmt(nowTime) + "(" + nowTime + ")", "ConnectStateUtil");
        SharedPreferencesUtil.save(context, key, nowTime);
        if (key.equals(MatrixConstant.KEY_MATRIX)) {
            recordMatrixTime = nowTime;
        }
    }

    /**
     * 检查矩阵连接状态
     *
     * @param context 上下文对象
     * @param key     保存数据的Key
     * @param timout  超时时间（毫秒）
     */
    public static void checkConnectStateMatrix(Context context, String key, long timout) {
        //||!TextUtils.isEmpty(App.selfCheckGUID)||!TextUtils.isEmpty(App.audioGUID)
        if (TextUtils.isEmpty(App.configInfo.getMatrixIP())) return;
        if (!App.matrixIPNetState) {
            BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_IP_UNCONNECT);
            LogUtil.add("提示", "本机网络与中控网络不通！", "矩阵");
            return;
        }
        long nowTime = new Date().getTime();
        long diff = nowTime - recordMatrixTime;
        LogUtil.add("计时", "记录矩阵数据接收时间="+recordMatrixTime+" 偏移量="+diff, "矩阵连接状态检查", false);
        if (!App.configInfo.isMatrixState()) {
            long time = (timout - diff) / 1000;
            if (time < 0) {
                time = 0;
            }
            LogUtil.add("计时", time + "秒后尝试重连！", "矩阵", false);
        }
        BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECONNECT_Timer);
        if (diff > timout) {
            recordTime(context, key);
            BackgroundService.reConnectingMatrix = false;
            LogUtil.add("重连", "超过" + timout + "毫秒没有收到服务器消息，尝试重连。", "矩阵");
            BroadcastUtil.sendMatrixBroadcast(MatrixConstant.TYPE_MATRIX_RECONNECT);
        }
    }

}
